package com.zzj.websocket;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.zzj.base.Result;
import com.zzj.entity.User;
import com.zzj.model.dto.websocket.ReqDto;
import com.zzj.service.WebSocketService;
import com.zzj.utils.JWTUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@ChannelHandler.Sharable
@Slf4j
@Component
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private  WebSocketService webSocketService;



    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("WS连接");
        webSocketService.connect(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        log.info("WS断开");
        webSocketService.removed(ctx.channel());
        ctx.channel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 异常处理
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //读到的客户端信息的逻辑处理
        //获取客户端发送的消息内容
        String jsonStr = textWebSocketFrame.text();
        log.info("接收到的消息：{}", jsonStr);
        ReqDto reqDto = JSON.parseObject(jsonStr, ReqDto.class);
        if (Objects.equals(reqDto.getType(), "login")) {
            webSocketService.handleUserLoginReq(ctx.channel());
        }else if (Objects.equals(reqDto.getType(), "heartbeat")) {
            webSocketService.sendMsg(ctx.channel(), new Result<>("WS心跳检测", "pong"));
        } else if (Objects.equals(reqDto.getType(), "authorization")) {
            String token = reqDto.getData().toString();
            if (!token.isEmpty() && JWTUtil.verify(token)) {
                JWTUtil.getUsername(token);
                User user = JWTUtil.getUser(token);
                webSocketService.addOnline(ctx.channel(), user);
                webSocketService.sendMsg(ctx.channel(), new Result<>("WS用户验证", true));
            }else{
                webSocketService.sendMsg(ctx.channel(), new Result<>("WS用户验证", false));
            }
        }
    }


}
